package org.chen.aao.user.service.email;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.concurrent.CompletableFuture;

@Slf4j
@Service
@RequiredArgsConstructor
public class EmailService {
    
    private final JavaMailSender mailSender;
    
    @Value("${spring.mail.username}")
    private String fromEmail;
    
    @Value("${app.mail.from-name:AI工具箱}")
    private String fromName;
    
    /**
     * 发送HTML邮件
     */
    public void sendHtmlEmail(String to, String subject, String htmlContent) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
            
            helper.setFrom(fromEmail, fromName);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(htmlContent, true);
            
            // 异步发送邮件
            CompletableFuture.runAsync(() -> {
                try {
                    mailSender.send(message);
                    log.info("邮件发送成功: to={}, subject={}", to, subject);
                } catch (Exception e) {
                    log.error("邮件发送失败: to={}, subject={}, error={}", to, subject, e.getMessage());
                    throw new RuntimeException("邮件发送失败", e);
                }
            });
            
        } catch (MessagingException | java.io.UnsupportedEncodingException e) {
            log.error("构建邮件失败: to={}, subject={}, error={}", to, subject, e.getMessage());
            throw new RuntimeException("邮件发送失败", e);
        }
    }
}